<template>
    <div class="addBrand-container" id="company-add-app">
        <div class="container">
            <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="true" label-width="180px"
                class="demo-ruleForm">
                <div class="horizontal-div">
                    <el-form-item label="公司名称:" prop="name">
                        <el-input v-model="ruleForm.name" placeholder="请填写公司名称" maxlength="20" />
                    </el-form-item>
                    <el-form-item label="公司分类:" prop="idType">
                        <el-select v-model="ruleForm.idType" placeholder="请选择公司分类" @change="$forceUpdate()">
                            <el-option v-for="(item, index) in setMealList" :key="index" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                </div>

                <div class="horizontal-div">
                    <el-form-item label="公司地址:" prop="address">
                        <el-input v-model="ruleForm.address" placeholder="请填写公司地址" maxlength="20" />
                    </el-form-item>
                </div>

                <div class="horizontal-div">
                    <el-form-item label="公司模型:" class="companyFood">
                        <el-form-item>
                            <div class="addModel">
                                <span v-if="modelTable.length == 0" class="addBut" @click="openAddModel" style="float: left;"> + 添加模型</span>
                                <div v-if="modelTable.length != 0" class="content" style="float: left;">
                                    <div class="addBut" style="margin-bottom: 20px;float: left;" @click="openAddModel">+ 继续添加模型</div>
                                    <div class="table">
                                        <el-table :data="modelTable" style="width: 100%">
                                            <el-table-column prop="name" label="名称" width="180"
                                                align="center"></el-table-column>
                                            <el-table-column prop="categoryName" label="类型" width="180"></el-table-column>
                                            <el-table-column label="操作" width="180px;" align="center">
                                                <template slot-scope="scope">
                                                    <el-button type="text" size="small"
                                                        @click="delModelHandle(scope.$index)"> 删除 </el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </el-form-item>
                </div>

                <div class="horizontal-div">
                    <el-form-item label="公司图片:" class="uploadImg">
                        <el-upload class="avatar-uploader" action="http://42.192.90.134:81/common/upload" :show-file-list="false"
                            :on-success="handleImageSuccess" :on-change="onChange" ref="upload" style="float: left;">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </div>
                <div class="horizontal-div">
                    <el-form-item label="公司Logo:" class="uploadImg">
                        <el-upload class="avatar-uploader" action="http://42.192.90.134:81/common/upload" :show-file-list="false"
                            :on-success="handleLogoSuccess" :on-change="onChange" ref="upload" style="float: left;">
                            <img v-if="logoUrl" :src="logoUrl" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </div>

                <div class="horizontal-div">
                    <div class="address">
                        <el-form-item label="公司描述:">
                            <el-input v-model="ruleForm.description" type="textarea" :rows="3" placeholder="公司描述，最长200字"
                                maxlength="200" />
                        </el-form-item>
                    </div>
                </div>


                <div class="subBox address">
                    <el-form-item>
                        <el-button @click="goBack()"> 取消 </el-button>
                        <el-button type="primary" @click="submitForm('ruleForm', false)"> 保存 </el-button>
                        <el-button v-if="actionType == 'add'" type="primary" class="continue"
                            @click="submitForm('ruleForm', true)">
                            保存并继续添加公司
                        </el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>

        <!-- 添加模型对话框 -->
        <el-dialog title="添加模型" class="addModelList" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
            <el-input v-model="value" class="seachModel" placeholder="请输入模型名称进行搜索" style="width: 250px" size="small"
                clearable>
                <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer" @click="seachHandle"></i>
            </el-input>

            <div class="addModelCon">
                <div class="leftCont">
                    <div v-show="seachKey.trim() == ''" class="tabBut">
                        <span v-for="(item, index) in modelType" :key="index" :class="{ act: index == keyInd }"
                            @click="checkTypeHandle(index, item.id)">{{ item.name }}</span>
                    </div>

                    <div class="tabList">
                        <div class="table">
                            <div v-if="modelAddList.length == 0" style="padding-left:10px">
                                暂无模型!
                            </div>
                            <el-checkbox-group v-if="modelAddList.length > 0" v-model="checkedListIds"
                                @change="checkedListHandle">
                                <div v-for="(item, index) in modelAddList" :key="index" class="items">
                                    <el-checkbox :key="index" :label="item.id">
                                        <div class="item">
                                            <span style="flex: 3; text-align: left">{{ item.name }}</span>
                                            <span>{{ item.status == 0 ? '隐藏' : '展示' }}</span>
                                            <span>{{ item.categoryName }}</span>
                                        </div>
                                    </el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>

                <div class="ritCont">
                    <div class="tit">
                        已选模型({{ checkedList.length }})
                    </div>
                    <div class="items">
                        <div v-for="(item, ind) in checkedList" :key="ind" class="item">
                            <span>{{ item.name }}</span>
                            <span class="categoryName">{{ item.categoryName }} </span>
                            <span class="del" @click="delCheck(ind)">
                                <img src="../../assets/images/icons/btn_clean@2x.png" alt="">
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="addTableList">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
  
<script>
// Import Vue, element-ui, and other dependencies here
import { queryCompanyById, addCompany, editCompany } from "../../api/company"; // Adjust import paths accordingly
import { queryModelList, getCategoryList } from '../../api/model'
import {download,upload,uploadModel} from '../../api/common'


export default {
    data() {
        return {
            id: "",
            actionType: "",
            value: "",
            setMealList: [],
            seachKey: "",
            modelList: [],
            imageUrl: "",
            logoUrl:"",
            modelTable: [],
            dialogVisible: false,
            checkList: [],
            ruleForm: {
                name: "",
                address:"",
                categoryId: "",
                // modelPath: "",
                code: "",
                image: "",
                logo:"",
                description: "",
                modelList: [],
                status: true,
                idType: "",
            },
            modelType: [],
            modelAddList: [],
            modelAddListAll:[],
            addedModelsSet: new Set(),
            modelListCache: [],
            keyInd: 0,
            searchValue: "",
            checkedList: [],
            checkedListIds:[]
        };
    },
    computed: {
        rules() {
            return {
                name: {
                    required: true,
                    message: "请输入公司名称",
                    trigger: "blur",
                },
                address: {
                    required: true,
                    message: "请输入公司地址",
                    trigger: "blur",
                },
                idType: {
                    required: true,
                    message: "请选择公司分类",
                    trigger: "change",
                },
                // modelPath: {
                //   required: false,
                //   // 'message': '请输入公司价格',
                //   validator: (rules, value, callback) => {
                //       if (!value) {
                //         callback(new Error('请填写模型价格'))
                //       } else {
                //         const reg = /^\d+(\.\d{0,2})?$/
                //         if (reg.test(value)) {
                //           if(value < 10000){
                //             callback()
                //           }else{
                //             callback(new Error('模型价格小于10000'))
                //           }
                //         } else {
                //           callback(new Error('模型价格格式只能为数字,且最多保留两位小数'))
                //         }
                //       }
                //     },
                //   trigger: 'blur',
                // },
            };
        },
    },
    watch: {
        seachKey(value) {
            if (value.trim()) {
                this.getModelForName(this.seachKey);
            }
        },
        checkList(value) {
            this.checkedList = value;
        },
    },
    created() {
        this.getModelTypeList();
        this.getModelType();
        this.id = this.$route.params.id;
        console.log("this.id:" + this.id)
        this.actionType = this.id ? "edit" : "add";
        if (this.id) {
            this.init();
        }
    },
    mounted() { },
    methods: {
        async init() {
            queryCompanyById(this.id).then((res) => {
                if (String(res.code) === '1') {
                    this.ruleForm = res.data
                    this.ruleForm.status = res.data.status === '1'
                    // this.ruleForm.modelPath = res.data.modelPath
                    
                    // TODO:这里的imageUrl需要更改到
                    this.imageUrl = res.data.image
                    this.logoUrl=res.data.logo

                    this.checkList = res.data.companyModels
                    this.modelTable = res.data.companyModels

                    // 初始化checkedList
                    this.checkedListIds = this.modelTable.map(model => model.id);

                    this.ruleForm.idType = res.data.categoryId
                    // this.ruleForm.password = ''
                } else {
                    this.$message.error(res.data.msg || '操作失败')
                }
            })
        },
        // 添加模型
        openAddModel() {
            this.seachKey = ''
            this.dialogVisible = true
            //搜索条件清空，模型重新查询，模型类别选第一个重新查询
            this.value = ''
            this.keyInd = 0
            this.getModelList(this.modelType[0].id)
        },
        // 通过公司ID获取模型列表分类
        getModelList(id) {
            queryModelList({ categoryId: id }).then(res => {
                if (res.code === 1) {
                    console.log("res.data.length:" + res.data.length)
                    if (res.data.length == 0) {
                        this.modelAddList = []
                        return
                    }
                    let newArr = res.data;
                    newArr.forEach((n) => {
                        // n.modelId = n.id
                        // n.copies = 1
                        // n.modelCopies = 1
                        // n.modelName = n.name
                        if (!this.addedModelsSet.has(n.modelId)) {
                        
                        this.modelAddListAll.push(n); // 将公司信息添加到modelAddListAll中
                        this.addedModelsSet.add(n.modelId);
                    }
                    })
                    this.modelAddList = newArr
                    console.log("this.modelAddList[0].name:" + this.modelAddList[0].name)
                    console.log("this.modelAddList[0].categoryName:" + this.modelAddList[0].categoryName)
                } else {
                    this.$message.error(res.data.msg)
                }
            })
        },
        checkTypeHandle(ind, id) {
            this.keyInd = ind
            this.getModelList(id)
        },
        // 获取添加模型数据
        getCheckList(value) {
            this.checkList = [...value]
        },
        checkedListHandle(checkedIds) {
            console.log("checkedIds:"+checkedIds)
            // 根据checkedIds更新checkedList
            this.checkedList = this.modelAddListAll.filter(item => this.checkedListIds.includes(item.id));

            this.getCheckList(this.checkedList)
        },
        seachHandle() {
            this.seachKey = this.value
        },
        // 获取公司分类
        getModelTypeList() {
            getCategoryList({ type: 2 }).then((res) => {
                if (res.code === 1) {
                    this.setMealList = res.data.map((obj) => ({ ...obj, idType: obj.id }))
                } else {
                    this.$message.error(res.data.msg || '操作失败')
                }
            })
        },
        // 删除公司模型
        delModelHandle(index) {
            this.modelTable.splice(index, 1)
            this.checkList.splice(index, 1)
        },
        // 取消添加模型
        handleClose(done) {
            // this.$refs.addmodel.close()
            this.dialogVisible = false
            this.checkList = JSON.parse(JSON.stringify(this.modelTable))
            // this.dialogVisible = false
        },

        // 保存添加模型列表
        addTableList() {
            this.modelTable = JSON.parse(JSON.stringify(this.checkList))
            // this.modelTable.forEach((n) => {
            //   n.copies = 1
            // })
            this.dialogVisible = false
            // 添加处理逻辑清空选中list
            this.checkList = []
        },
        submitForm(formName, st) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let prams = { ...this.ruleForm }
                    // prams.modelPath *= 100
                    prams.companyModels = this.modelTable.map((obj) => ({
                        modelId: obj.modelId,
                        name: obj.name,
                        categoryName: obj.categoryName,
                    }))
                    prams.status = this.ruleForm ? 1 : 0
                    prams.categoryId = this.ruleForm.idType
                    if (prams.companyModels.length < 1) {
                        this.$message.error('请选择模型！')
                        return
                    }
                    if (!this.imageUrl) {
                        this.$message.error('请上传公司图片')
                        return
                    }
                    if (!this.logoUrl) {
                        this.$message.error('请上传公司Logo')
                        return
                    }
                    // delete prams.modelList
                    if (this.actionType == 'add') {
                        addCompany(prams)
                            .then((res) => {
                                if (res.code === 1) {
                                    this.$message.success('公司添加成功！')
                                    if (!st) {
                                        this.goBack()
                                    } else {
                                        this.$refs.ruleForm.resetFields()
                                        this.modelList = []
                                        this.modelTable = []
                                        this.ruleForm = {
                                            name: '',
                                            address:'',
                                            categoryId: '',
                                            categoryName: '',
                                            code: '',
                                            image: '',
                                            logo:'',
                                            description: '',
                                            modelList: [],
                                            status: true,
                                            id: '',
                                            idType: '',
                                        }
                                        this.imageUrl = ''
                                        this.logoUrl=''
                                    }
                                } else {
                                    this.$message.error(res.data.msg || '操作失败')
                                }
                            })
                            .catch((err) => {
                                this.$message.error('请求出错了：' + err)
                            })
                    } else {
                        delete prams.updateTime
                        editCompany(prams)
                            .then((res) => {
                                if (res.code === 1) {
                                    this.$message.success('公司修改成功！')
                                    this.goBack()
                                } else {
                                    this.$message.error(res.data.msg || '操作失败')
                                }
                            })
                            .catch((err) => {
                                this.$message.error('请求出错了：' + err)
                            })
                    }
                } else {
                    return false
                }
            })
        },
        handleImageSuccess(response, file, fileList) {
            // this.imageUrl = response.data
            if (response.code === 0 && response.msg === '未登录') {
                window.top.location.href = '/backend/page/login/login.html'
            } else {
                this.imageUrl = `http://42.192.90.134:8082/images/${response.data}`
                this.ruleForm.image = response.data
                
            }
        },
        handleLogoSuccess(response, file, fileList) {
            // this.imageUrl = response.data
            if (response.code === 0 && response.msg === '未登录') {
                window.top.location.href = '/backend/page/login/login.html'
            } else {
                this.logoUrl = `http://42.192.90.134:8082/images/${response.data}`
                this.ruleForm.logo = response.data
                
            }
        },

        onChange(file) {
            if (file) {
                const suffix = file.name.split('.')[1]
                const size = file.size / 1024 / 1024 < 2
                if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                    this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                    this.$refs.upload.clearFiles()
                    return false
                }
                if (!size) {
                    this.$message.error('上传文件大小不能超过 2MB!')
                    return false
                }
                return file
            }
        },
        goBack() {
            window.parent.menuHandle(
                {
                    id: '5',
                    url: '/backend/page/company/list.html',
                    name: '公司管理',
                },
                false
            )
            this.$router.back();
        },
        // 获取模型分类
        getModelType() {
            getCategoryList({ 'type': 1 }).then(res => {
                if (res.code === 1) {
                    this.modelType = res.data
                    if(res.data.length!=0){
                        this.getModelList(res.data[0].id)
                    }
                    
                } else {
                    this.$message.error(res.data.msg)
                }
            })
        },

        // 关键词收搜模型列表分类
        getModelForName(name) {
            queryModelList({ name }).then(res => {
                if (res.code === 1) {
                    let newArr = res.data
                    newArr.forEach((n) => {
                        n.modelId = n.id
                        n.modelName = n.name
                    })
                    this.modelAddList = newArr
                } else {
                    this.$message.error(res.data.msg)
                }
            })
        },

        open(done) {
            this.modelListCache = JSON.parse(JSON.stringify(this.checkList))
        },

        close(done) {
            this.checkList = this.modelListCache
        },

        // 删除
        delCheck(ind) {
            this.checkedList.splice(ind, 1)
        }
    },
};
</script>
  
<style scoped>
/* Add your styles here */
.horizontal-div {
    display: flex;
    align-items: center;
    /* 可根据需要调整垂直间距 */
}

.addModel .el-input {
    width: 130px;
}

.addModel .el-input-number__increase {
    border-left: solid 1px #FFE1CA;
    background: #fff3ea;
}

.addModel .el-input-number__decrease {
    border-right: solid 1px #FFE1CA;
    background: #fff3ea;
}

.addModel input {
    border: 1px solid #ffe1ca;
}

.addModel .table {
    border: solid 1px #EBEEF5;
    border-radius: 3px;
}

.addModel .table th {
    padding: 5px 0;
}

.addModel .table td {
    padding: 7px 0;
}

.addModelList .seachModel {
    position: absolute;
    top: 10px;
    right: 20px;
}

.addModelList .el-dialog__body {
    padding: 0;
    border-bottom: solid 1px #ccc;
}

.addModelList .el-dialog__footer {
    padding-top: 27px;
}

.addModel {
    width: 777px;
}

.addModel .addBut {
    background: #ffc200;
    display: inline-block;
    padding: 0px 20px;
    border-radius: 3px;
    line-height: 40px;
    cursor: pointer;
    border-radius: 4px;
    color: #333333;
    font-weight: 500;
}

.addModel .content {
    background: #fafafb;
    padding: 20px;
    border: solid 1px #ccc;
    border-radius: 3px;
}

.addModelCon {
    padding: 0 20px;
    display: flex;
    line-height: 40px;
}

.addModelCon .leftCont {
    display: flex;
    border-right: solid 2px #E4E7ED;
    width: 60%;
    padding: 15px;
}

.addModelCon .leftCont .tabBut {
    width: 110px;
}

.addModelCon .leftCont .tabBut span {
    display: block;
    text-align: center;
    border-right: solid 2px #f4f4f4;
    cursor: pointer;
}

.addModelCon .leftCont .act {
    border-color: #FFC200 !important;
    color: #FFC200 !important;
}

.addModelCon .leftCont .tabList {
    flex: 1;
    padding: 15px;
}

.addModelCon .leftCont .tabList .table {
    border: solid 1px #f4f4f4;
    border-bottom: solid 1px #f4f4f4;
}

.addModelCon .leftCont .tabList .table .items {
    border-bottom: solid 1px #f4f4f4;
    padding: 0 10px;
    display: flex;
}

.addModelCon .leftCont .tabList .table .items .el-checkbox,
.addModelCon .leftCont .tabList .table .items .el-checkbox__label {
    width: 100%;
}

.addModelCon .leftCont .tabList .table .items .item {
    display: flex;
    padding-right: 20px;
}

.addModelCon .leftCont .tabList .table .items .item span {
    display: inline-block;
    text-align: center;
    flex: 1;
}

.addModelCon .ritCont {
    width: 40%;
    padding: 0 15px;
}

.addModelCon .ritCont .item {
    box-shadow: 0px 1px 4px 3px rgba(0, 0, 0, 0.03);
    display: flex;
    text-align: center;
    padding: 0 10px;
    margin-bottom: 20px;
    border-radius: 6px;
    color: #818693;
}

.addModelCon .ritCont .item span:first-child {
    text-align: left;
    color: #20232A;
}

.addModelCon .ritCont .item .modelPath {
    display: inline-block;
    flex: 1;
}

.addModelCon .ritCont .item .del {
    cursor: pointer;
}

.addModelCon .ritCont .item .del img {
    position: relative;
    top: 5px;
    width: 20px;
}

.addModelCon .el-checkbox__label {
    width: 100%;
}

#company-add-app .companyFood .el-form-item__label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}

#company-add-app .uploadImg .el-form-item__label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}
</style>
  